import { login, logout, getInfo, getMenuList } from '@/api/login'
import { getToken, setToken, removeToken, getUserId, setUserId, removeUserId,getComanyId, setComanyId, removeComanyId,setRoleType,removeRoleType } from '@/utils/auth'
let storage = window.localStorage;
const user = {
  state: {
    token: getToken(),
    name: '',
    avatar: '',
    roles: [],
    menu: []
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_NAME: (state, name) => {
      state.name = name
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
     SET_MENU: (state, list) => {
      state.menu = list
    }
  },

  actions: {
    // 登录
    Login({ commit }, userInfo) {
      const username = userInfo.account.trim()
      return new Promise((resolve, reject) => {
        login(username, userInfo.password, userInfo.randomCode ).then(response => {
          const data = response.entity;
          commit('SET_NAME', data.user.name)
          commit('SET_TOKEN', data.token);
					setUserId(data.user.id);
          setToken(data.token);
          setComanyId(data.user.companyId);
          if(data.roleList.length>0){
            setRoleType(data.roleList[0].type)
          };
          if(data.deptList&&data.deptList.length>0){
            storage.setItem("deptList",JSON.stringify(data.deptList));
          }
         
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 获取用户信息
    GetMenuList({ commit ,state }){
    	return new Promise((resolve, reject) => {
    		const userId = getUserId();
        getMenuList(userId).then(response => {
          const data = response.entity;
          commit('SET_MENU',data);
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 登出
    LogOut({ commit, state }) {
      return new Promise((resolve, reject) => {
        logout(state.token).then(() => {
          commit('SET_TOKEN', '')
          commit('SET_ROLES', [])
          removeToken()
          removeUserId()
          removeComanyId()
          removeRoleType()
          storage.setItem('deptList',null);
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 前端 登出
    FedLogOut({ commit }) {
      return new Promise(resolve => {
        resolve()
      })
    }
  }
}

export default user
